package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.bean.Article;
import com.demo.common.Result;
import com.demo.mapper.ArticleMapper;
import com.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;

    @Override
    public Result findById(Integer id) {
        if (-1 == id) {
            QueryWrapper<Article> wrapper = new QueryWrapper();
            return Result.ok().success(articleMapper.selectList(wrapper));
        } else {
            return Result.ok().success(articleMapper.selectById(id));
        }
    }

    @Override
    public Result findByTitle(String title) {
        return Result.ok().success(articleMapper.findByTitle(title));
    }

    @Override
    public Result findPage(Integer pageId, Integer pageSize) {
        if (null != pageId && null != pageSize) {
            Page<Article> page = new Page<>(pageId, pageSize);
            IPage<Article> iPage = articleMapper.selectArticlePage(page);
            return Result.ok().success(iPage);
        } else {
            return Result.ok().error("分页信息不可为空");
        }
    }

    @Override
    @Transactional
    public Result insert(List<Article> articleList) {
        if (null != articleList && articleList.size() > 0) {

            int i = articleMapper.add(articleList);
            if (i > 0) {
                return Result.ok("插入成功");
            } else {
                return Result.error("插入失败");
            }
        } else {
            return Result.error("传入信息不可为空");
        }


    }

    @Override
    public Result update(Article article) {
        if (null != article && null != article.getId() && !"".equals(article.getId().toString())) {
            int i = articleMapper.updateById(article);
            if (i > 0) {
                return Result.ok("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } else {
            return Result.error("更新信息不可为空");
        }

    }

    @Override
    public Result delete(List<Long> ids) {

        if (null != ids && ids.size() > 0) {
            int i = articleMapper.deleteList(ids);
            if (i > 0) {
                return Result.ok("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } else {
            return Result.error("id不可为空");
        }

    }


}
